<template>
  <el-card>
    <template #header>添加账号</template>
    <div>
      <el-button
        type="danger"
        size="mini"
        class="del-more"
        @click="handleDelete(false)"
        >批量删除</el-button
      >
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60"> </el-table-column>
        <el-table-column prop="id" label="ID" width="100px"> </el-table-column>

        <el-table-column prop="username" label="用户名称" width="200px">
        </el-table-column>

        <el-table-column prop="group_id" label="账号权限" width="150px">
          <template v-slot="{ row }">
            <el-tag v-if="row.group_id === 1">超级管理员</el-tag>
            <el-tag type="warning" v-else>普通管理员</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间"> </el-table-column>

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="mini" @click="handleEdit(row)"> 编辑 </el-button>

            <el-button size="mini" type="danger" @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>

        <el-dialog
          title="账号编辑"
          :visible.sync="dialogVisible"
          width="50%"
          @close="handleClose"
        >
          <el-form
            :model="accountForm"
            :rules="rules"
            ref="ruleForm"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名称" prop="username">
              <el-input
                type="text"
                v-model="accountForm.username"
                autocomplete="off"
                placeholder="请输入用户名称"
                prefix-icon="iconfont icon-yonghu1"
              ></el-input>
            </el-form-item>

            <el-form-item label="账号权限" prop="group_id">
              <el-select
                v-model="accountForm.group_id"
                clearable
                placeholder="请选择"
              >
                <el-option label="超级权限" value="1"></el-option>
                <el-option label="普通权限" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="dialogVisible = false">
              取 消
            </el-button>
            <el-button size="small" type="primary" @click="editAccount">
              确 定
            </el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </el-card>
</template>

<script>
import { userList, delList, editList } from '@/api/users.js'

export default {
  data() {
    var validateaccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名称'))
      } else {
        callback()
      }
    }
    var validateuserGroup = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择用户权限'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      multipleSelection: [],
      dialogVisible: false,
      curItem: '',
      accountForm: {
        username: '',
        group_id: ''
      },
      rules: {
        username: [{ validator: validateaccount, trigger: 'blur' }],
        group_id: [{ validator: validateuserGroup, trigger: 'change' }]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      // 获取本地数据的 token 和 member_id
      const users = JSON.parse(localStorage.getItem('users') || '{}')
      const { data, count } = await userList({
        member_id: users.member_id,
        access_token: users.access_token,
        page: this.currentPage,
        limit: this.pageSize
      })
      // console.log(data)
      // console.log(count)
      this.tableData = data
      this.total = count
    },
    handleEdit(r) {
      // r.group_id = r.group_id + ''
      this.accountForm = JSON.parse(JSON.stringify(r))
      this.accountForm.group_id = this.accountForm.group_id + ''
      this.dialogVisible = true
    },
    handleDelete(id) {
      let ids = ''
      if (id) {
        // 单项删除
        ids = id
      } else {
        // 批量删除
        // filter - 过滤器，会把满足条件的每一项返回
        // map - 会把满足条件的每一项的指定内容返回
        const arr = this.multipleSelection.map((item) => item.id)
        // console.log(arr,1)
        ids = arr.join()
      }

      // 如果当前的列表没有任何数据了，直接改变页码
      if (this.tableData.length <= 1) {
        this.currentPage--
      }

      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // })
          // 当用户点击确定删除的时候，需要发请求
          // 获取本地数据的 token 和 member_id
          const users = JSON.parse(localStorage.getItem('users') || '{}')
          const { code, msg } = await delList({
            member_id: users.member_id,
            access_token: users.access_token,
            ids: ids
          })
          if (code === 1) {
            this.$message.success(msg)
            this.getUserList()
          } else {
            this.$message.error(msg)
          }
          // console.log(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    batchDel() {},
    handleClose() {
      this.$refs.ruleForm.resetFields()
    },
    editAccount() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 验证通过，可以添加用户
          // 获取本地数据的 token 和 member_id
          const users = window.localStorage.getItem('users') || '{}'
          const token = JSON.parse(users).access_token
          const { code, msg } = await editList({
            member_id: JSON.parse(users).member_id,
            access_token: JSON.parse(users).access_token,
            username: this.accountForm.username,
            group_id: this.accountForm.group_id - 0,
            id: this.accountForm.id
          })
          if (code === 1) {
            // element-ui 提供了一个页面的提示组件
            this.$message.success(msg) // 固定格式
            this.getUserList()
            this.dialogVisible = false
          } else {
            this.$message.error(msg)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUserList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  .del-more {
    margin: 10px 0 10px 0;
  }
  .el-form-item {
    width: 380px;
    .el-select {
      width: 300px;
    }
  }
}
</style>
